import platform, os, urllib2, gobject
from thread2 import Thread

def updatePlugins(pymaxe):
	if os.environ.get("APPDATA"):
		pymaxeDir = os.environ.get("APPDATA") + '\\pymaxe'
	else:
		pymaxeDir = os.getenv("HOME") + '/.pymaxe'
	
	liststore = pymaxe.gui.get_object('liststore2')
	iter = liststore.get_iter_root()
	plist = []
	while (iter):
		pluginName = liststore.get_value(iter, 3)
		plugin = pymaxe.plugin[pluginName]
		
		if hasattr(plugin, 'updatecheck'):
			#checkUpdates(pluginName, pluginVersion, pluginCheck)
			Thread(target=checkUpdates, args=(plugin, pymaxe)).start()
		iter = liststore.iter_next(iter)
		
def checkUpdates(plugin, pymaxe):
	req = urllib2.Request(plugin.updatecheck)
	response = urllib2.urlopen(req)
	data = response.read()
	toUpdate = []
	if ':update:' in data:
		s = data.split(':update:')
		try:
			cVer = float(plugin.version)
			nVer = float(s[0])
			if cVer < nVer:
				toUpdate.append([plugin, s[1]])
		except:
			pass
	
	Thread(target=doUpdatePlugins, args=(toUpdate, pymaxe)).start()
	
def doUpdatePlugins(plugins, pymaxe):
	gobject.idle_add(pymaxe.gui.get_object('progressbar1').set_text, 'Updating plugins...')
	pymaxe.isWorking = True
	if os.environ.get("TMP"):
		tmp = os.environ.get('TMP') + '\\'
	else:
		tmp = '/tmp/'
	
	for x in plugins:
		try:
			url = x[1]
			if os.path.basename(url)[-4:] == '.zip':
				req = urllib2.Request(url)
				response = urllib2.urlopen(req)
				data = response.read()
				temp = tmp + os.path.basename(url)
				fh = open(temp, 'wb')
				fh.write(data)
				fh.close()
				gobject.idle_add(pymaxe.doPluginInstall, temp, False)
		except Exception, e:
			print e
	gobject.idle_add(pymaxe.gui.get_object('progressbar1').set_text, '')
	pymaxe.isWorking = False
